package com.qingyun.system.plugin.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.qingyun.system.common.base.BaseEntity;
import com.qingyun.system.security.model.SysUserDetails;
import com.qingyun.system.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * mybatis-plus 字段自动填充
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增填充创建时间
     *
     * @param metaObject 元数据对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("在插入操作时,自动填充修改人和修改时间字段,metaObject:{}", metaObject);
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            // 自动填充创建时间
            this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
            // 自动填充更新时间
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
            // 自动填充创建人、修改人
            SysUserDetails currentUser = SecurityUtils.getUser();
            if (currentUser != null && Objects.nonNull(currentUser.getUserId())) {
                this.strictInsertFill(metaObject, "createBy", () -> currentUser.getUserId(), Long.class);
                this.strictUpdateFill(metaObject, "updateBy", () -> currentUser.getUserId(), Long.class);
            }
        }
    }

    /**
     * 更新填充更新时间
     *
     * @param metaObject 元数据
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("在更新操作时,自动填充修改人和修改时间字段,metaObject:{}", metaObject);
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
            SysUserDetails currentUser = SecurityUtils.getUser();
            if (currentUser != null && Objects.nonNull(currentUser.getUserId())) {
                this.strictUpdateFill(metaObject, "updateBy", () -> currentUser.getUserId(), Long.class);
            }
        }
    }

}
